var loginImageId = S4() + S4();
var asynQueryWeixinImageUrlStateFlag = 0;
var loginQrCodeScannedFlag = false;// 是否已扫码
$(function () {
    validateKickout();
    validateRule();

    // 更换验证码
    $('.imgcode').click(function () {
        var url = ctx + "captcha/captchaImage?type=" + captchaType + "&s=" + Math.random();
        $(".imgcode").attr("src", url);
    });

    // 更换登录二维码
    $('.qrloginimg').click(function () {
        loginImageId = S4() + S4();
        getLoginImge(loginImageId);
    });

    // 切换登录方式
    $('.loginType1').click(function () {
        loginImageId = S4() + S4();
        getLoginImge(loginImageId);
        $(".login-tab-1").attr("style", "display:none");
        $(".login-tab-2").attr("style", "display:block");
    });
    $('.loginType2').click(function () {
        $(".login-tab-1").attr("style", "display:block");
        $(".login-tab-2").attr("style", "display:none");
    });
});

/**
 * 生成随机数
 */
function S4() {
    // 0x   表示16进制数据的开头
    //可以直接return (((1+Math.random())*0x10000)|0).toString(16)；

    //也可用如下，随机数*时间戳，再转化为16进制
    //Number.toString(16)    表示将其转换为16进制
    // Number | 0 表示取整数部分

    let stamp = new Date().getTime();
    return (((1 + Math.random()) * stamp) | 0).toString(16);
}


$.validator.setDefaults({
    submitHandler: function () {
        login();
    }
});

function login() {
    $.modal.loading($("#btnSubmit").data("loading"));
    var username = $.common.trim($("input[name='username']").val());
    var password = $.common.trim($("input[name='password']").val());
    var validateCode = $("input[name='validateCode']").val();
    var rememberMe = $("input[name='rememberme']").is(':checked');
    $.ajax({
        type: "post",
        url: ctx + "login",
        data: {
            "username": username,
            "password": password,
            "validateCode": validateCode,
            "rememberMe": rememberMe
        },
        success: function (r) {
            if (r.code == web_status.SUCCESS) {
                loginImageId = null;
                asynQueryWeixinImageUrlStateFlag = 0;
                location.href = ctx + 'index';
            } else {
                $.modal.closeLoading();
                $('.imgcode').click();
                $(".code").val("");
                $.modal.msg(r.msg);
            }
        }
    });
}

function validateRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#signupForm").validate({
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            }
        },
        messages: {
            username: {
                required: icon + "请输入您的用户名",
            },
            password: {
                required: icon + "请输入您的密码",
            }
        }
    })
}

function validateKickout() {
    if (getParam("kickout") == 1) {
        layer.alert("<font color='red'>您已在别处登录，请您修改密码或重新登录</font>", {
                icon: 0,
                title: "系统提示"
            },
            function (index) {
                //关闭弹窗
                layer.close(index);
                if (top != self) {
                    top.location = self.location;
                } else {
                    var url = location.search;
                    if (url) {
                        var oldUrl = window.location.href;
                        var newUrl = oldUrl.substring(0, oldUrl.indexOf('?'));
                        self.location = newUrl;
                    }
                }
            });
    }
}

function getParam(paramName) {
    var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}

function getLoginImge(loginImageId) {
    if (!loginImageId)
        return;
    var url = ctx + "getWeixinLoginImage?loginImageId=" + loginImageId;
    $(".qrloginimg").attr("src", url);
    // console.log(loginImageId)
    if (loginImageId){
        asynQueryWeixinImageUrlState();
    } else{
        // 显示重新获取的遮罩
    }
}

function asynQueryWeixinImageUrlState() {
    if(asynQueryWeixinImageUrlStateFlag == 0){
        asynQueryWeixinImageUrlStateFlag = 1;
        setTimeout(function () {
            queryWeixinImageUrlState();
        }, 1500)
    }
}

// 查询登录二维码状态
function queryWeixinImageUrlState() {
    if (!loginImageId && asynQueryWeixinImageUrlStateFlag == 1)
        return;
    asynQueryWeixinImageUrlStateFlag = 2;
    // $.modal.loading($("#queryWeixinImageUrlState").data("loading"));
    $.ajax({
        type: "post",
        url: ctx + "getWeixinLoginImageState",
        data: {
            "loginImageId": loginImageId
        },
        success: function (r) {
            console.log(r)
            if (r.code == web_status.SUCCESS && r.msg == "LOGIN_SUCCEEDED") {
                // 登录成功
                location.href = ctx + 'index';
                loginQrCodeScannedFlag = false;
            } else if(r.code == web_status.SUCCESS && r.msg == "INVALID"){
                // 失效的二维码
                loginQrCodeScannedFlag = false;
                $.modal.closeLoading();
                $.modal.alertError('二维码已过期，请重试获取登录二维码')
            } else if(r.code == web_status.SUCCESS
                && (r.msg == "NOT_LOGGED" || r.msg == "CODE_SCANNED")){
                // 有效未登录的、扫码未确认的
                asynQueryWeixinImageUrlStateFlag = 0;
                asynQueryWeixinImageUrlState();

                // 显示已扫码，请确认的遮罩
                if(!loginQrCodeScannedFlag && r.msg == "CODE_SCANNED"){
                    $.modal.loading("已扫码，请确认登录");
                    loginQrCodeScannedFlag = true;
                }

            } else {
                loginQrCodeScannedFlag = false;
                asynQueryWeixinImageUrlStateFlag = 0;
                $.modal.closeLoading();
                // $.modal.msg(r.msg);
                // 请求失败时更换ID，防止二次错误
                loginImageId = S4() + S4();
                $.modal.alertWarning(r.msg)
            }
        }
    });
}